package com.atjinggu.jinggumail.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atjinggu.jinggumail.common.utils.HttpUtils;
import com.atjinggu.jinggumail.member.entity.MemberLevelEntity;
import com.atjinggu.jinggumail.member.exception.PhoneExistException;
import com.atjinggu.jinggumail.member.exception.UsernameExistException;
import com.atjinggu.jinggumail.member.service.MemberLevelService;
import com.atjinggu.jinggumail.member.vo.MemberLoginVo;
import com.atjinggu.jinggumail.member.vo.MemberRegistVo;
import com.atjinggu.jinggumail.member.vo.SocialUser;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atjinggu.jinggumail.common.utils.PageUtils;
import com.atjinggu.jinggumail.common.utils.Query;

import com.atjinggu.jinggumail.member.dao.MemberDao;
import com.atjinggu.jinggumail.member.entity.MemberEntity;
import com.atjinggu.jinggumail.member.service.MemberService;

@Slf4j
@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelService memberLevelService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo)  {

        log.info("retist user ================ "+vo.getUserName() + ":"+vo.getPhone());
        MemberEntity entity = new MemberEntity();
        MemberLevelEntity memberLevelEntity = memberLevelService.getBaseMapper().selectOne(new QueryWrapper<MemberLevelEntity>().eq("default_status", "1"));
        entity.setLevelId(memberLevelEntity.getId());

        checkUsernameUnique(vo.getUserName());
        checkPhoneUnique(vo.getPhone());

        entity.setUsername(vo.getUserName());
        entity.setNickname(vo.getUserName());
        entity.setMobile(vo.getPhone());

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        entity.setPassword(encoder.encode(vo.getPassword()));
        baseMapper.insert(entity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException{
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if(count > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUsernameUnique(String userName) throws UsernameExistException{
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if(count > 0) {
            throw new UsernameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginAcct = vo.getLoginAcct();
        String password = vo.getPassword();

        MemberEntity entity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginAcct).or().eq("mobile", loginAcct));
        if(entity == null){
            return null;
        }

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        boolean matches = encoder.matches(password, entity.getPassword());
        if(!matches){
            return null;
        }
        return entity;
    }

    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        MemberEntity entity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", socialUser.getUid()));
        if(entity != null){
            MemberEntity update = new MemberEntity();
            update.setSocialUid(socialUser.getUid());
            update.setExpiresIn(socialUser.getExpires_in());
            update.setAccessToken(socialUser.getAccess_token());

            this.baseMapper.updateById(update);

            entity.setAccessToken(socialUser.getAccess_token());
            entity.setExpiresIn(socialUser.getExpires_in());
            return entity;
        }
        MemberEntity memberEntity =  new MemberEntity();
        try {
            HashMap<String, String> query = Maps.newHashMap();
            query.put("access_token", socialUser.getAccess_token());
            query.put("uid", socialUser.getUid());
            //查出社交用户的社交信息（昵称，性别，年龄等）
            HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);
            if (response.getStatusLine().getStatusCode() == 200) {
                String json = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSON.parseObject(json);
                String gender = jsonObject.getString("gender");
                String name = jsonObject.getString("name");
                //........
                memberEntity.setNickname(name);
                memberEntity.setGender("m".equalsIgnoreCase(gender) ? 0 : 1);
            }
        }catch (Exception e){
            log.error("查询社交用户信息失败!",e);
        }
        memberEntity.setAccessToken(socialUser.getAccess_token());
        memberEntity.setExpiresIn(socialUser.getExpires_in());
        memberEntity.setSocialUid(socialUser.getUid());
        this.baseMapper.insert(memberEntity);
        return memberEntity;
    }

}